package com.fary.typehandle;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Component
@MappedTypes(List.class)
@MappedJdbcTypes({JdbcType.CHAR, JdbcType.VARCHAR})
public class ListTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        strings.removeIf(StrUtil::isBlank);
        preparedStatement.setString(i, StrUtil.join(",", strings));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return CollectionUtil.distinct(CollectionUtil.removeBlank(StrUtil.split(resultSet.getString(s), ",")));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return CollectionUtil.distinct(CollectionUtil.removeBlank(StrUtil.split(resultSet.getString(i), ",")));
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return CollectionUtil.distinct(CollectionUtil.removeBlank(StrUtil.split(callableStatement.getString(i), ",")));
    }
}
